// copy from minio
package signature

import (
	"net/http"
	"net/url"
	"strings"
	"time"
)

const (
	yyyymmdd          = "20060102"
	SlashSeparator    = "/"
	signV4Algorithm   = "AWS4-HMAC-SHA256"
	iso8601Format     = "20060102T150405Z"
	unsignedPayload   = "UNSIGNED-PAYLOAD"
	iso8601DateFormat = "20060102T150405Z"

	// Dummy putBucketACL
	AmzACL = "x-amz-acl"

	// Signature V4 related contants.
	AmzContentSha256        = "X-Amz-Content-Sha256"
	StreamingBodySha256     = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"
	AmzDate                 = "X-Amz-Date"
	AmzAlgorithm            = "X-Amz-Algorithm"
	AmzExpires              = "X-Amz-Expires"
	AmzSignedHeaders        = "X-Amz-SignedHeaders"
	AmzSignature            = "X-Amz-Signature"
	AmzCredential           = "X-Amz-Credential"
	AmzSecurityToken        = "X-Amz-Security-Token"
	AmzDecodedContentLength = "X-Amz-Decoded-Content-Length"

	LastModified       = "Last-Modified"
	Date               = "Date"
	ETag               = "ETag"
	ContentType        = "Content-Type"
	ContentMD5         = "Content-Md5"
	ContentEncoding    = "Content-Encoding"
	Expires            = "Expires"
	ContentLength      = "Content-Length"
	ContentLanguage    = "Content-Language"
	ContentRange       = "Content-Range"
	Connection         = "Connection"
	AcceptRanges       = "Accept-Ranges"
	AmzBucketRegion    = "X-Amz-Bucket-Region"
	ServerInfo         = "Server"
	RetryAfter         = "Retry-After"
	Location           = "Location"
	CacheControl       = "Cache-Control"
	ContentDisposition = "Content-Disposition"
	Authorization      = "Authorization"
	Action             = "Action"
	Range              = "Range"

	// Signature v2 related constants
	AmzSignatureV2 = "Signature"
	AmzAccessKeyID = "AWSAccessKeyId"

	// Signature and API related constants.
	signV2Algorithm = "AWS"

	// Response request id.
	AmzRequestID = "x-amz-request-id"

	DefaultZone = "DEFAULT"
)

// credentialHeader data type represents structured form of Credential
// string from authorization header.
type credentialHeader struct {
	accessKey      string
	scopeStr       string
	scopeWithoutAk string
	scope          struct {
		date    time.Time
		dateStr string
		region  string
		service string
		request string
	}
}

// parse credentialHeader string into its structured form.
func parseCredentialHeader(credElement string, region string) (ch credentialHeader, aec APIErrorCode) {
	creds := strings.SplitN(strings.TrimSpace(credElement), "=", 2)
	if len(creds) != 2 {
		return ch, ErrMissingFields
	}
	if creds[0] != "Credential" {
		return ch, ErrMissingCredTag
	}

	credElements := strings.Split(strings.TrimSpace(creds[1]), SlashSeparator)
	if len(credElements) < 5 {
		return ch, ErrCredMalformed
	}
	accessKey := strings.Join(credElements[:len(credElements)-4], SlashSeparator) // The access key may contain one or more `/`
	// Save access key id.
	cred := credentialHeader{
		accessKey: accessKey,
	}
	cred.scopeStr = creds[1]
	credElements = credElements[len(credElements)-4:]
	cred.scopeWithoutAk = strings.Join(credElements, SlashSeparator)
	var e error
	cred.scope.dateStr = credElements[0]
	cred.scope.date, e = time.Parse(yyyymmdd, credElements[0])
	if e != nil {
		return ch, ErrMalformedCredentialDate
	}

	cred.scope.region = credElements[1]

	cred.scope.service = credElements[2]
	if credElements[3] != "aws4_request" {
		return ch, ErrInvalidRequestVersion
	}
	cred.scope.request = credElements[3]
	return cred, ErrNone
}

// Parse signature from signature tag.
func parseSignature(signElement string) (string, APIErrorCode) {
	signFields := strings.Split(strings.TrimSpace(signElement), "=")
	if len(signFields) != 2 {
		return "", ErrMissingFields
	}
	if signFields[0] != "Signature" {
		return "", ErrMissingSignTag
	}
	if signFields[1] == "" {
		return "", ErrMissingFields
	}
	signature := signFields[1]
	return signature, ErrNone
}

// Parse slice of signed headers from signed headers tag.
func parseSignedHeader(signedHdrElement string) ([]string, string, APIErrorCode) {
	signedHdrFields := strings.Split(strings.TrimSpace(signedHdrElement), "=")
	if len(signedHdrFields) != 2 {
		return nil, "", ErrMissingFields
	}
	if signedHdrFields[0] != "SignedHeaders" {
		return nil, "", ErrMissingSignHeadersTag
	}
	if signedHdrFields[1] == "" {
		return nil, "", ErrMissingFields
	}
	signedHeaders := strings.Split(signedHdrFields[1], ";")
	return signedHeaders, signedHdrFields[1], ErrNone
}

// signValues data type represents structured form of AWS Signature V4 header.
type signValues struct {
	Credential        credentialHeader
	SignedHeaderStr   string // SignedHeaders=amz-sdk-invocation-id;amz-sdk-retry;clientversion
	SignedHeaderValue string // amz-sdk-invocation-id;amz-sdk-retry;clientversion
	SignedHeaders     []string
	Signature         string
}

// preSignValues data type represents structued form of AWS Signature V4 query string.
type preSignValues struct {
	signValues
	Date    time.Time
	Expires time.Duration
}

// Parses signature version '4' query string of the following form.
//
//	querystring = X-Amz-Algorithm=algorithm
//	querystring += &X-Amz-Credential= urlencode(accessKey + '/' + credential_scope)
//	querystring += &X-Amz-Date=date
//	querystring += &X-Amz-Expires=timeout interval
//	querystring += &X-Amz-SignedHeaders=signed_headers
//	querystring += &X-Amz-Signature=signature
//
// verifies if any of the necessary query params are missing in the presigned request.
func doesV4PresignParamsExist(query url.Values) APIErrorCode {
	v4PresignQueryParams := []string{AmzAlgorithm, AmzCredential, AmzSignature, AmzDate, AmzSignedHeaders, AmzExpires}
	for _, v4PresignQueryParam := range v4PresignQueryParams {
		if _, ok := query[v4PresignQueryParam]; !ok {
			return ErrInvalidQueryParams
		}
	}
	return ErrNone
}

// Parses all the presigned signature values into separate elements.
func parsePreSignV4(query url.Values, region string) (psv preSignValues, aec APIErrorCode) {
	// verify whether the required query params exist.
	aec = doesV4PresignParamsExist(query)
	if aec != ErrNone {
		return psv, aec
	}

	// Verify if the query algorithm is supported or not.
	if query.Get(AmzAlgorithm) != signV4Algorithm {
		return psv, ErrInvalidQuerySignatureAlgo
	}

	// Initialize signature version '4' structured header.
	preSignV4Values := preSignValues{}

	// Save credential.
	preSignV4Values.Credential, aec = parseCredentialHeader("Credential="+query.Get(AmzCredential), region)
	if aec != ErrNone {
		return psv, aec
	}

	var e error
	// Save date in native time.Time.
	preSignV4Values.Date, e = time.Parse(iso8601Format, query.Get(AmzDate))
	if e != nil {
		return psv, ErrMalformedPresignedDate
	}

	// Save expires in native time.Duration.
	preSignV4Values.Expires, e = time.ParseDuration(query.Get(AmzExpires) + "s")
	if e != nil {
		return psv, ErrMalformedExpires
	}

	if preSignV4Values.Expires < 0 {
		return psv, ErrNegativeExpires
	}

	// Check if Expiry time is less than 7 days (value in seconds).
	if preSignV4Values.Expires.Seconds() > 604800 {
		return psv, ErrMaximumExpires
	}

	// Save signed headers.
	preSignV4Values.SignedHeaders, preSignV4Values.signValues.SignedHeaderValue, aec = parseSignedHeader("SignedHeaders=" + query.Get(AmzSignedHeaders))
	if aec != ErrNone {
		return psv, aec
	}

	// Save signature.
	preSignV4Values.Signature, aec = parseSignature("Signature=" + query.Get(AmzSignature))
	if aec != ErrNone {
		return psv, aec
	}

	// Return structed form of signature query string.
	return preSignV4Values, ErrNone
}

// Parses signature version '4' header of the following form.
//
//	Authorization: algorithm Credential=accessKeyID/credScope, \
//	        SignedHeaders=signedHeaders, Signature=signature
func parseSignV4(v4Auth string, region string) (sv signValues, aec APIErrorCode) {
	// credElement is fetched first to skip replacing the space in access key.
	credElement := strings.TrimPrefix(strings.Split(strings.TrimSpace(v4Auth), ",")[0], signV4Algorithm)
	// Replace all spaced strings, some clients can send spaced
	// parameters and some won't. So we pro-actively remove any spaces
	// to make parsing easier.
	v4Auth = strings.Replace(v4Auth, " ", "", -1)
	if v4Auth == "" {
		return sv, ErrAuthHeaderEmpty
	}

	// Verify if the header algorithm is supported or not.
	if !strings.HasPrefix(v4Auth, signV4Algorithm) {
		return sv, ErrSignatureVersionNotSupported
	}

	// Strip off the Algorithm prefix.
	v4Auth = strings.TrimPrefix(v4Auth, signV4Algorithm)
	authFields := strings.Split(strings.TrimSpace(v4Auth), ",")
	if len(authFields) != 3 {
		return sv, ErrMissingFields
	}

	// Initialize signature version '4' structured header.
	signV4Values := signValues{}

	var s3Err APIErrorCode
	// Save credentail values.
	signV4Values.Credential, s3Err = parseCredentialHeader(strings.TrimSpace(credElement), region)
	if s3Err != ErrNone {
		return sv, s3Err
	}

	signV4Values.SignedHeaderStr = authFields[1]
	// Save signed headers.
	signV4Values.SignedHeaders, signV4Values.SignedHeaderValue, s3Err = parseSignedHeader(authFields[1])
	if s3Err != ErrNone {
		return sv, s3Err
	}

	// Save signature.
	signV4Values.Signature, s3Err = parseSignature(authFields[2])
	if s3Err != ErrNone {
		return sv, s3Err
	}

	// Return the structure here.
	return signV4Values, ErrNone
}

func GetAccessKeyFromSignatureV4(r *http.Request) (string, error) {
	preSign, aes := parsePreSignV4(r.URL.Query(), "")
	if aes == ErrNone {
		return preSign.Credential.accessKey, nil
	}

	if aes == ErrInvalidQueryParams {
		sign, aes2 := parseSignV4(r.Header.Get(Authorization), "")
		if aes2 != ErrNone {
			return "", errorCodes.ToAPIErr(aes2)
		}
		return sign.Credential.accessKey, nil
	}
	return "", errorCodes.ToAPIErr(ErrAuthHeaderEmpty)
}

type SignatureType int

func (st SignatureType) IsPreSign() bool {
	return st == PreSign
}

const (
	PreSign SignatureType = iota + 1
	NormalSign
)

// GetAccessKey 从 http 请求中获取ak, 并且返回该 ak 来源于哪个签名算法
func GetAccessKeyWithSignType(r *http.Request) (ak string, source SignatureType, err error) {
	preSign, aes := parsePreSignV4(r.URL.Query(), "")
	if aes == ErrNone {
		return preSign.Credential.accessKey, PreSign, nil
	}

	if aes == ErrInvalidQueryParams {
		sign, aes2 := parseSignV4(r.Header.Get(Authorization), "")
		if aes2 != ErrNone {
			return "", PreSign, errorCodes.ToAPIErr(aes2)
		}
		return sign.Credential.accessKey, NormalSign, nil
	}
	return "", NormalSign, errorCodes.ToAPIErr(ErrAuthHeaderEmpty)
}
